using System;
using System.Globalization;
using System.Collections.Generic;
using System.Text;
using Microsoft.Build.Utilities;
using Microsoft.Build.Framework;

namespace TFSAssemblyInfoTask
{
	public class ConvertTFSBuildNumberToSolutionBuildNumber : Task
	{
		private string tfsBuildNumber;
		private string tfsLastBuildNumber;
		private string minorAndMajorVersion;
		private string solutionBuildNumber;

		public string MajorAndMinorVersion
		{
			get { return minorAndMajorVersion; }
			set { minorAndMajorVersion = value; }
		}

		[Output]
		public string TFSBuildNumber
		{
			get { return tfsBuildNumber; }
			set
			{
				if (string.IsNullOrEmpty(value))
					throw new ArgumentNullException("value", "Parameter TFSBuildNumber must have a value");
				tfsBuildNumber = value;
			}
		}

		public string TFSLastBuildNumber
		{
			get { return tfsLastBuildNumber; }
			set { tfsLastBuildNumber = value; }
		}

		[Output]
		public string SolutionBuildNumber
		{
			get { return solutionBuildNumber; }
		}

		public override bool Execute()
		{
			try
			{
				Version version = new Version(minorAndMajorVersion, tfsLastBuildNumber, tfsBuildNumber);
				version.Update();
				tfsBuildNumber = version.TFSBuildNumber;
				solutionBuildNumber = version.ToString();
				return true;
			}
			catch (Exception e)
			{
				Log.LogErrorFromException(e, true);
				return false;
			}
		}
	}
}
